package org.yuangu.privacyfinance.activities;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.privacy.accountmgr.R;

import org.yuangu.privacyfinance.activities.helper.FullTaskListener;
import org.yuangu.privacyfinance.domain.FinanceDatabase;
import org.yuangu.privacyfinance.helpers.KeyStoreHelper;
import org.yuangu.privacyfinance.helpers.KeyStoreHelperException;
import org.yuangu.privacyfinance.helpers.SharedPreferencesManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class StartupActivity extends AppCompatActivity implements FullTaskListener {
    ProgressBar progressBar;
    TextView    progressText;
    boolean keyGen = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferencesManager.init(getApplicationContext());
        setContentView(R.layout.activity_startup);
        getSupportActionBar().hide();
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        progressText = findViewById(R.id.progressText);
        progressBar = findViewById(R.id.progressBar);
        if (FinanceDatabase.getInstance() == null) {
            try {
                if (!KeyStoreHelper.getInstance(FinanceDatabase.KEY_ALIAS).keyExists()) {
                    keyGen = true;
                    progressText.setVisibility(View.VISIBLE);
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setMax(1000);
                }
            } catch (KeyStoreHelperException e) {
                e.printStackTrace();
            }

            FinanceDatabase.connect(getApplicationContext(), this);
        } else {
            nextActivity();
        }
    }

    @Override
    public void onDone(Object result, AsyncTask<?, ?, ?> task) {
        nextActivity();
    }

    private void nextActivity() {
        Intent   mainIntent = new Intent(this, TransactionsActivity.class);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(mainIntent);
        finish();
    }

    @Override
    public void onProgress(final Double progress, AsyncTask<?, ?, ?> task) {
        if (keyGen)
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressBar.setProgress(Double.valueOf(progress * 1000).intValue());
                }
            });
    }

    @Override
    public void onOperation(final String operation, AsyncTask<?, ?, ?> task) {
        if (keyGen)
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressText.setText(operation);
                }
            });
    }
}
